package com.paw.qrcode.config;

import com.paw.qrcode.handler.MpMessageDefaultHandler;
import com.paw.qrcode.handler.MpMessageLogHandler;
import com.paw.qrcode.handler.MpMessageScanHandler;
import me.chanjar.weixin.common.api.WxConsts.EventType;
import me.chanjar.weixin.common.api.WxConsts.XmlMsgType;
import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.config.WxMpConfigStorage;
import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author lvzihai
 * @date 2022/6/23
 **/


  @Configuration
  @ConditionalOnClass(WxMpService.class)
  @EnableConfigurationProperties(WechatMpProperties.class)
  public class WechatMpConfiguration {

    @Autowired
    WechatMpProperties mpProperties;

    @Autowired
    MpMessageLogHandler logHandler;
    @Autowired
    MpMessageScanHandler scanHandler;
    @Autowired
    MpMessageDefaultHandler mpMessageDefaultHandler;

    @Bean
    @ConditionalOnMissingBean
    public WxMpConfigStorage configStorage() {
      WxMpDefaultConfigImpl configStorage = new WxMpDefaultConfigImpl();
      configStorage.setAppId(this.mpProperties.getAppId());
      configStorage.setSecret(this.mpProperties.getSecret());
      configStorage.setToken(this.mpProperties.getToken());
      configStorage.setAesKey(this.mpProperties.getAesKey());
      return configStorage;
    }

    @Bean
    @ConditionalOnMissingBean
    public WxMpService wxMpService(WxMpConfigStorage configStorage) {
      WxMpService wxMpService = new me.chanjar.weixin.mp.api.impl.WxMpServiceImpl();
      wxMpService.setWxMpConfigStorage(configStorage);
      return wxMpService;
    }

    @Bean
    public WxMpMessageRouter router(WxMpService wxMpService) {
      final WxMpMessageRouter newRouter = new WxMpMessageRouter(wxMpService);

      // 记录所有事件的日志 （异步执行）
      newRouter.rule().handler(this.logHandler).next();

      // 扫码事件
      newRouter.rule().async(false).msgType(XmlMsgType.EVENT)
          .event(EventType.SCAN).handler(this.scanHandler).end();

      // 默认
      newRouter.rule().async(false).handler(this.mpMessageDefaultHandler).end();

      return newRouter;
    }



}
